import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:image_pickers/image_pickers.dart';
import 'package:yuan_hang_app/http/api.dart';
import 'package:yuan_hang_app/http/app_response.dart';
import 'package:yuan_hang_app/http/http_utils.dart';
import 'package:yuan_hang_app/utils/router_helper.dart';
import 'package:yuan_hang_app/utils/size_utils.dart';
import 'package:yuan_hang_app/widget/photo_view.dart';
import 'package:yuan_hang_app/widget/w_toast.dart';

import '../../../../../res/w_colors.dart';
import '../../../../../res/w_dimens.dart';
import '../../../../../widget/image_picker.dart';
import '../../../../../widget/w_text.dart';
import 'package:http_parser/http_parser.dart';

//上传附件控件
class CommonAttachment extends StatefulWidget {
  final int count; //图片可选择最多张数
  final List? picList; //已有的图片列表
  final List? picUrlList; //已有的图片列表
  final bool enabled; //是否可编辑
  final Function(List picList, List<Map> images)? onSelected; //图片回调
  final EdgeInsets? margin;
  final Key? key;

  const CommonAttachment(
      {this.key,
      this.count = 5,
      this.picList,
      this.picUrlList,
      this.enabled = true,
      this.margin,
      this.onSelected})
      : super(key: key);

  @override
  CommonAttachmentState createState() => CommonAttachmentState();
}

class CommonAttachmentState extends State<CommonAttachment> {
  List<Map> _attachmentImages = [
    {"image": "images/plus.png", "type": 0}
    //type=0，添加 type==1//文件 type=2,//上传url地址
  ];
  int maxCount = 5;
  List pictureList = [];
  bool enabled = true;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    maxCount = widget.count;
    enabled = widget.enabled;
    pictureList = widget.picList ?? [];
    for (var item in widget.picUrlList ?? []) {
      _attachmentImages
          .insert(_attachmentImages.length - 1, {"image": item, "type": 2});
    }
    if (!enabled || _attachmentImages.length > maxCount) {
      _attachmentImages.removeLast();
    }
  }

  void refreshList(list) {
    for (var item in list) {
      _attachmentImages
          .insert(_attachmentImages.length, {"image": item, "type": 2});
    }
    if (!isConPlus() && enabled && _attachmentImages.length < maxCount) {
      _attachmentImages.add({"image": "images/plus.png", "type": 0});
    }

    setState(() {});
  }

  void refreshImageList(
    List<Map> images,
  ) {
    if (images.isNotEmpty) {
      _attachmentImages = images;
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        margin: widget.margin,
        padding: EdgeInsets.symmetric(horizontal: 15.px, vertical: 5.px),
        color: Colors.white,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            WText(
              "附件",
              style: TextStyle(
                  color: WColors.mainTextColor, fontSize: WDimens.tsLabel),
            ),
            GridView.builder(
              shrinkWrap: true,
              padding: EdgeInsets.only(bottom: 10.px, top: 5.px),
              physics: const NeverScrollableScrollPhysics(),
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  mainAxisSpacing: 0.px,
                  crossAxisCount: 4,
                  crossAxisSpacing: 0.px,
                  childAspectRatio: 1),
              itemBuilder: _picItemBuilder,
              itemCount: _attachmentImages.length,
            )
          ],
        ));
  }

  Widget _picItemBuilder(context, index) {
    Map item = _attachmentImages[index];
    return GestureDetector(
      onTap: () {
        if (item["type"] == 0) {
          ImagePicker.showImagePicker(
              context: context,
              count: maxCount - getPicList().length,
              onSelected: (paths) async {
                int picLength = pictureList.length;
                //  print("================length========$picLength");
                if (paths != null && paths.length > 0) {
                  Toast.showLoading(text: "上传中...");
                  for (int i = 0; i < paths.length; i++) {
                    uploadImage(paths[i]).then((value) {
                      if (value.resultCode == 200) {
                        if (value.data["resultCode"] != null &&
                            value.data["resultCode"] == 200) {
                          _attachmentImages.insert(_attachmentImages.length - 1,
                              {"image": paths[i], "type": 1});
                          setState(() {});
                          pictureList.add(value.data["data"]["fileUploadId"]);
                          if (_attachmentImages.length > maxCount) {
                            _attachmentImages.removeLast();
                            setState(() {});
                          }
                          //  print("================length========$i-----$picLength");
                          if ((pictureList.length - picLength) ==
                              paths.length) {
                            Toast.dismissLoading();
                            if (widget.onSelected != null) {
                              widget.onSelected!(
                                  pictureList, _attachmentImages);
                            }
                          }
                        } else if (value.data["resultCode"] != null &&
                            value.data["resultCode"] == 500) {
                          Toast.dismissLoading();
                          Toast.toast(value.data["data"]["errMsg"]);
                        }
                      } else {
                        Toast.dismissLoading();
                        Toast.toast(value.errMsg);
                      }
                    }).catchError((e) {
                      Toast.dismissLoading();
                    });
                  }
                }
              });
        } else {
          //ImagePickers.previewImages(getPicList(), index);
          RouteHelper.pushWidget(
              context, PhotoView(imgs: getPicList(), currentIndex: index));
        }
      },
      child: Stack(children: [
        Container(
            width: (SizeUtils.screenW() - 100.px) / 4,
            height: (SizeUtils.screenW() - 100.px) / 4,
            margin: EdgeInsets.only(top: 5.px),
            //  color: Colors.green,
            child: getImageItem(item)),
        Positioned(
          top: 0,
          right: 5.0.px,
          child: GestureDetector(
            onTap: () {
              if (_attachmentImages.length == 1 &&
                  _attachmentImages[0]["type"] == 0) {
                return;
              }
              _attachmentImages.removeAt(index);
              if (_attachmentImages.length == maxCount - 1 &&
                  _attachmentImages[_attachmentImages.length - 1]["type"] !=
                      0) {
                _attachmentImages.add({"image": "images/plus.png", "type": 0});
              }
              setState(() {});
              // if(pictureList.length>index)
              pictureList.removeAt(index);
              if (widget.onSelected != null) {
                widget.onSelected!(pictureList, _attachmentImages);
              }
            },
            child: item["type"] == 0 || !enabled
                ? const SizedBox()
                : Image.asset(
                    "images/ic_del_pic.png",
                    width: 15.px,
                  ),
          ),
        )
      ]),
    );
  }

  List<String> getPicList() {
    List<String> pic = [];
    for (Map item in _attachmentImages) {
      if (item["type"] != 0) {
        pic.add(item["image"]);
      }
    }
    return pic;
  }

  bool isConPlus() {
    for (Map item in _attachmentImages) {
      if (item["type"] == 0) {
        return true;
      }
    }
    return false;
  }

  Widget getImageItem(item) {
    return SizedBox(
      //   width: (SizeUtils.screenW() - 120.px) / 4,
      // height: (SizeUtils.screenW() - 120.px) / 4,
      child: item["type"] == 0
          ? Image.asset(
              item["image"],
              fit: BoxFit.cover,
            )
          : item["type"] == 1
              ? Image.file(
                  File(item["image"]),
                  fit: BoxFit.cover,
                )
              : FadeInImage(
                  placeholder: const AssetImage("images/ic_loading_b.png"),
                  imageErrorBuilder: (cxt, ob, s) => Image.asset(
                        "images/image_error.png",
                      ),
                  fit: BoxFit.cover,
                  image: NetworkImage(item["image"].toString())),
    );
  }

  ///上传图片
  static Future<AppResponse> uploadImage(filePath) {
    FormData formData = FormData.fromMap({
      'file': MultipartFile.fromFileSync(filePath,
          contentType: MediaType.parse("image/jpeg"))
    });

    return HttpUtils().post(Api.uploadFile2, data: formData).then((onValue) {
      return onValue;
    });
  }
}
